/*
 * Copyright (c) 2013 Johan Fylling
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights 
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 * THE SOFTWARE.
 */

part of tools;


typedef StorageHandler (StorageManager manager, Map attributes);
typedef StorageTagListener (final dynamic obj);


class StorageManager implements Service {
  static final Logging.Logger                 _logger       = new Logging.Logger("drones.tools.storage_manager");
  final Map<String, StorageHandler>           _handlers     = new Map<String, StorageHandler>();
  final Map<String, List<StorageTagListener>> _tagListeners = new Map<String, List<StorageTagListener>>();
  final Map<String, dynamic>                  _tags         = new Map<String, dynamic>();
  
  void setHandler (String key, StorageHandler handler) {
    _handlers[key] = handler;
  }
  
  loadFile (String path) {
    _logger.fine('Downloading file "$path".');
    HttpRequest request = new HttpRequest();
    request.open('GET', path, false);
    request.onLoad.listen((e) {
      if (request.status >= 200 && request.status < 300 ||
          request.status == 304 ) {
        _logger.fine('File "$path" downloaded.');
        _logger.finer('HTTP status ${request.status}.');
        _logger.finest('File download completed: ${request.responseText}');
        loadJson(request.responseText);
      } else {
        _logger.severe('File download failed with status: ${request.status}');
      }
    });
    request.onError.listen((e) {
      _logger.severe('File download failed with error: $e');
    });
    request.send();
  }
  
  loadJson (String data) {
    _tags.clear();
    try {
      var attributes = json.parse(data);
      assert(attributes is Map);
      return load(attributes);
    } on FormatException catch (e) {
      _logger.severe('invalid JSON: $e');
    }
  }
  
  load (Map attributes) {
    var type = attributes["type"];
    assert(type is String);
    _logger.finer('Loading Handler for "$type"');
    _logger.finest('$attributes');
    StorageHandler handler = _handlers[type];
    if (handler != null) {
      var result = handler(this, attributes);
      var tag = attributes["tag"];
      if (tag != null) {
        assert(tag is String);
        _addTag(tag, result);
      }
      return result;
    } else {
      _logger.severe('Found no Handler for "$type"');
    }
  }
  
  String storeJson (data) {
    return json.stringify(data);
  }
  
  void onTag (String tag, StorageTagListener listener) {
    List<StorageTagListener> listeners = _tagListeners[tag];
    if (listeners == null) {
      listeners = new List<StorageTagListener>();
      _tagListeners[tag] = listeners;
    }
    listeners.add(listener);
    
    var data = _tags[tag];
    if (data != null) {
      listener(data);
    }
  }
  
  void _addTag (String tag, dynamic data) {
    _tags[tag] = data;
    List<StorageTagListener> listeners = _tagListeners[tag];
    if (listeners != null) {
      for (StorageTagListener listener in listeners) {
        if (listener != null) {
          listener(data);
        }
      }
    }
  }
}
